/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Addon SDK dependencies */
const _sdkNotifications = require('sdk/notifications');
const _sdkPreferencesService = require('sdk/preferences/service');
const _sdkConsole = console;

/* Used modules */
const _pMeta = require('./meta');
const _pOptions = require('./options');

const LOG_DEBUG = 0, LOG_INFO = 1, LOG_NOTICE = 2, LOG_WARNING = 3, LOG_ERROR = 4;
const LOG_MIN_NOTIFICATION = LOG_NOTICE;

const _names = ['Debug', 'Info', 'Notice', 'Warning', 'Error'];

const _notify = message => {
	const sdkNotifications = _sdkNotifications;
	const pMeta = _pMeta, pOptions = _pOptions;
	
	if (!pOptions.activeUiEnabled()) return false;
	
	return false !== sdkNotifications.notify({
		title: pMeta.getProductName() + '', text: message + ''
	});
};

const _setLevel = minLevel => {
	const sdkPreferencesService = _sdkPreferencesService; // XXX: Low-level SDK
	const pMeta = _pMeta;
	
	const prefName = `extensions.${pMeta.getProductID()}.sdk.console.logLevel`;
	const sdkLogLevel = ['debug', 'info', 'info', 'warn', 'error'][minLevel];
	sdkPreferencesService.set(prefName, sdkLogLevel);
};

// Assume messages are untrusted
const _log = (level, messages) => {
	const sdkConsole = _sdkConsole;
	const pOptions = _pOptions;
	
	try {
		// console.log() will be ignored by default
		// and so will console.info() (configurable by the user)
		const minLevel = pOptions.logAll() ? LOG_DEBUG
			:(pOptions.logDetails() ? LOG_INFO
				:(pOptions.logImportant() ? LOG_NOTICE : LOG_ERROR));
		_setLevel(minLevel); // based on addon preferences
		
		if (level >= minLevel) {
			// no 'notice' in Console API
			const date = `[${(new Date).toISOString()}]`;
			if (level == LOG_NOTICE) messages.unshift('Notice:');
			sdkConsole[['log', 'info', 'info', 'warn', 'error'][level]](date, ... messages);
		}
		if (level >= LOG_MIN_NOTIFICATION) {
			const name = level == LOG_NOTICE ? '' : _names[level];
			return _notify([name, ... messages].join(' '));
		}
		
		return true;
	} catch (e) { // unlikely to happen
		return false;
	}
};


/* Internal API */
const debug = (... messages) => _log(LOG_DEBUG, messages);
const info = (... messages) => _log(LOG_INFO, messages);
const notice = (... messages) => _log(LOG_NOTICE, messages);
const warning = (... messages) => _log(LOG_WARNING, messages);
const error = (... messages) => _log(LOG_ERROR, messages);

// Aliases
const warn = (... messages) => warning(... messages);
const err = (... messages) => error(... messages);
const notify = (... messages) => notice(... messages);
const showNotification = (... messages) => notice(... messages);

/* Exports */
exports.debug = debug;
exports.info = info;
exports.notice = notice;
exports.warning = warning;
exports.error = error;
exports.warn = warn;
exports.err = err;
exports.notify = notify;
exports.showNotification = showNotification;


// vim: ts=4 noet ai

